package org.zuel.huhuForum.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;
import org.zuel.huhuForum.constant.CommunityConstant;
import org.zuel.huhuForum.model.Message;
import org.zuel.huhuForum.model.User;
import org.zuel.huhuForum.param.Letter;
import org.zuel.huhuForum.param.Page;
import org.zuel.huhuForum.service.IMessageService;
import org.zuel.huhuForum.service.IUserService;
import org.zuel.huhuForum.util.HostHolder;
import java.time.LocalDateTime;
import java.util.*;
import static org.zuel.huhuForum.util.DesensitizeUtil.desensitize;

@Log4j2
@RestController
@RequestMapping("/message")
@Api(tags = "私信")
public class MessageController implements CommunityConstant {
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private IMessageService messageService;

    @Autowired
    private IUserService userService;

    /**
     * 私信列表
     * @param current
     * @return
     */
    @ApiOperation(value = "私信列表")
    @CrossOrigin
    @PostMapping("/letter/list")
    public Map getLetterList(@RequestParam(name = "current",required = false,defaultValue = "1") int current) {
        Page page=new Page();
        // Integer.valueOf("abc"); // 测试统一异常处理（普通请求）
        Map<String,Object>model=new HashMap<>();
        // 获取当前登录用户信息
        User user = hostHolder.getUser();
        // 分页信息
        page.setCurrent(current);
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCout(user.getId()));
        // 私信列表
        List<Message> conversationList = messageService.findConversations(
                user.getId(), page.getOffset(), page.getLimit());

        List<Map<String, Object>> conversations = new ArrayList<>();
        if (conversationList != null) {
            for (Message message : conversationList) {
                Map<String, Object> map = new HashMap<>();
                map.put("conversation", message); // 私信
                map.put("letterCount", messageService.findLetterCount(
                        message.getConversationId())); // 私信数量
                map.put("unreadCount", messageService.findLetterUnreadCount(
                        user.getId(), message.getConversationId())); // 未读私信数量
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target", userService.findUserById(targetId)); // 私信对方

                conversations.add(map);
            }
        }
        model.put("conversations", conversations);

        // 查询当前用户的所有未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.put("letterUnreadCount", letterUnreadCount);
        int noticeUnreadCount = messageService.findNoticeUnReadCount(user.getId(), null);
        model.put("noticeUnreadCount", noticeUnreadCount);
        model.put("page",page);
        return model;
    }

    /**
     * 私信详情页
     * @param conversationId
     * @return
     */
    @ApiOperation(value = "私信详情页")
    @CrossOrigin
    @PostMapping("/letter/detail")
    public Map<String, Object> getLetterDetail(@RequestParam(name="conversationId", required = true) String conversationId
            ){
        Map<String,Object>model=new HashMap<>();
        model.put("Count",messageService.findLetterCount(conversationId));
        // 私信列表
        List<Message> letterList = messageService.findLetters(conversationId);

        List<Letter> letters = new ArrayList<>();
        log.info(letterList.toString());
        if (letterList != null) {
            for (Message message : letterList) {
                Letter letter=new Letter();
                letter.setId(message.getId());
                letter.setFromId(message.getFromId());
                letter.setToId(message.getToId());
                letter.setStatus(message.getStatus());
                letter.setContent(message.getContent());
                letter.setCreateTime(message.getCreateTime());
                letter.setConversationId(message.getConversationId());
                letter.setUserName(userService.findUserById(message.getFromId()).getUsername());
                letters.add(letter);
            }
        }
        if(letterList.size()==0){
            model.put("msg", "codeMsg");
            model.put("code", "23");
            model.put("data", "未查询到数据");
            return model;
        }
        model.put("letters", letters);
        // 私信目标
        model.put("target", getLetterTarget(conversationId));
        // 将私信列表中的未读消息改为已读
        List<Integer> ids = getUnreadLetterIds(letterList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }
        return model;
    }

    private Integer getOffset(@RequestParam(name = "offset", required = false) Integer offset) {
        return offset;
    }
    /**
     * 获取私信对方对象
     * @param conversationId
     * @return
     */
    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if (hostHolder.getUser().getId() == id0) {
            return userService.findUserById(id1);
        }
        else {
            return userService.findUserById(id0);
        }
    }

    /**
     * 获取当前登录用户未读私信的 id
     * @param letterList
     * @return
     */
    private List<Integer> getUnreadLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                // 当前用户是私信的接收者且该私信处于未读状态
                if (hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }

    /**
     * 发送私信
     * @param toName 收信人 username
     * @param content 内容
     * @return
     */
    @CrossOrigin
    @ResponseBody
    @PostMapping("/letter/send")
    @ApiOperation(value = "发送私信")
    public Map<String, String> sendLetter(@RequestParam(name="toName", required = true)String toName,
                             @RequestParam(name="content", required = true)String content) {
        // Integer.valueOf("abc"); // 测试统一异常处理（异步请求）
        User target = userService.findUserByName(toName);
        Map<String, String> model=new HashMap<>();
        if (target == null) {
            model.put("msg", "codeMsg");
            model.put("code", "23");
            model.put("data", "查无此人");
            return model;
        }

        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        }
        else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setStatus(0); // 默认就是 0 未读，可不写
        message.setCreateTime(LocalDateTime.now());
        messageService.addMessage(message);

        model.put("msg", "codeMsg");
        model.put("code", "200");
        model.put("data", "添加成功");
        return model;
    }

    /**
     * 通知列表（只显示最新一条消息）
     * @return
     */
    @CrossOrigin
    @GetMapping("/notice/list")
    @ApiOperation(value = "通知列表（只显示最新一条消息）")
    public Map getNoticeList() {
        User user = hostHolder.getUser();
        Map<String,Object>model=new HashMap<>();
        // 查询评论类通知
        Message message = messageService.findLatestNotice(user.getId(), TOPIC_COMMNET);
        // 封装通知需要的各种数据
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", message);
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            messageVO.put("user", desensitize(userService.findUserById((Integer) data.get("userId"))));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));
            int count = messageService.findNoticeCount(user.getId(), TOPIC_COMMNET);
            messageVO.put("count", count);
            int unread = messageService.findNoticeUnReadCount(user.getId(), TOPIC_COMMNET);
            messageVO.put("unread", unread);

            model.put("commentNotice", messageVO);
        }

        // 查询点赞类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_LIKE);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();

            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", desensitize(userService.findUserById((Integer) data.get("userId"))));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_LIKE);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnReadCount(user.getId(), TOPIC_LIKE);
            messageVO.put("unread", unread);

            model.put("likeNotice", messageVO);
        }

        // 查询关注类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_FOLLOW);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();

            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", desensitize(userService.findUserById((Integer) data.get("userId"))));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnReadCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("unread", unread);

            model.put("followNotice", messageVO);
        }

        // 查询未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.put("letterUnreadCount", letterUnreadCount);
        int noticeUnreadCount = messageService.findNoticeUnReadCount(user.getId(), null);
        model.put("noticeUnreadCount", noticeUnreadCount);

        return model;
    }

    /**
     * 查询某个主题所包含的通知列表
     * @param topic
     * @param current

     * @return
     */
    @CrossOrigin
    @PostMapping("/notice/detail")
    @ApiOperation(value = "查询某个主题所包含的通知列表")
    public Map getNoticeDetail(@RequestParam(name = "topic",required = true)  String topic,
                               @RequestParam(name = "current",required = false) Integer current) {
        User user = hostHolder.getUser();
        Map<String,Object>model=new HashMap<>();
        Page page=new Page();
        if(current!=null){
            page.setCurrent(current);
        }
        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.findNoticeCount(user.getId(), topic));

        List<Message> noticeList = messageService.findNotices(user.getId(), topic,page.getOffset(), page.getLimit());
        List<Map<String, Object>> noticeVoList = new ArrayList<>();
        if (noticeList != null) {
            for (Message notice : noticeList) {
                Map<String, Object> map = new HashMap<>();
                // 通知
                map.put("notice", notice);
                // 内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user", desensitize(userService.findUserById((Integer) data.get("userId"))));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));
                // 发送系统通知的作者
                map.put("fromUser", desensitize(userService.findUserById(notice.getFromId())));

                noticeVoList.add(map);
            }
        }
        model.put("notices", noticeVoList);

        // 设置已读
        List<Integer> ids = getUnreadLetterIds(noticeList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }
        model.put("page",page);
        return model;
    }
}
